package com.jiyongjun.bms.base.module.login;

import com.jiyongjun.bms.base.common.util.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.Principal;

/**
 * <h2>登录相关控制器</h2>
 * description:
 *
 * @author yongjun.ji
 * @since 1.0 2019/6/3
 */
@Slf4j
@Controller
public class LoginController {

    @RequestMapping(value = {"/", "/login"})
    public String login(Principal principal) {
        if (principal == null) {
            return "/login";
        }
        return "/main/main";
    }

    @GetMapping(value = "/getCode")
    public void getCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpg");

            //生成随机字串
            String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
            log.info("verifyCode:{}", verifyCode);
            //存入会话session
            HttpSession session = request.getSession(true);
            session.setAttribute("_code", verifyCode.toLowerCase());
            //生成图片
            int w = 146, h = 33;
            VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
